package com.iman.manjusri.web;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Maps;
import com.iman.common.emaiUtil.MailSenderInfo;
import com.iman.common.emaiUtil.SimpleMailSender;
import com.iman.common.hibernate.HibernateSupport;
import com.iman.common.util.ConfigUtil;
import com.iman.common.util.DateUtils;
import com.iman.common.util.EncryptTool;
import com.iman.common.util.FreeMarkerUtils;
import com.iman.common.util.JsonUtil;
import com.iman.manjusri.domain.ProvinceCity;
import com.iman.manjusri.domain.User;
import com.iman.manjusri.repository.IRedisGo;
import com.iman.manjusri.service.AreaService;
import com.iman.manjusri.service.RegisterService;
import com.iman.manjusri.vo.CityCodeName;
import com.iman.manjusri.vo.CodeName;

@Controller
@RequestMapping(value = "/register/*")
public class MemberRegisterController extends BaseController {

	private  Logger logger = LoggerFactory.getLogger(MemberRegisterController.class);
	public static final String saveFileType = "register/";
	public static final String uploadfileperfix = "*.bmp,*.jpeg(*.jpg),*.tif,*.gif,*.png";

	@Inject
	RegisterService registerService;
	
	@Inject
	AreaService areaService;

    @Inject
    HibernateSupport hibernateSupport ; 
    
    
    @Inject
    IRedisGo redis;

 
    //图片的域名  	   
	 String imgbasePath  =ConfigUtil.getString( "image.server" );; 
	 //css 服务器连接    在 context.properties 配置
	 String cssbasePath  =ConfigUtil.getString( "css.server" );; 
	//js 	url base	服务器连接    在 context.properties 配置
	 String jsbasePath  =ConfigUtil.getString( "js.server" );; 
	 

	@RequestMapping(value = "/new")
	@ResponseBody
	public String register1(User user,String register_code_val , HttpServletRequest multipartRequest) throws Exception {
		 Map result = new  HashMap();
		//检查验证码
		
		String  checode  = (String)multipartRequest.getSession().getValue("randCheckCode");
		
		if(checode==null || !checode.equals(register_code_val)){
			result.put("code", 0);
		    result.put("msg", "验证码错误");
	        return JsonUtil.toJson(result);
		}
		
		
		
		//TODO需要检查是否有重复的 注册ID
		logger.info("注册："+user);
		List quie = this.hibernateSupport.findBy(User.class, "loginName", user.getLoginName())  ;
		
		if(quie!=null && quie.size()>0){
		 	result.put("code", 0);
		    result.put("msg", "注册的用户名已经存在");
	        return JsonUtil.toJson(result);
		}
		
		logger.info("没有重复："+user.getLoginName());

	    Long pk = this.registerService.saveUser(user);
	    
	    result.put("code", 1);
	    result.put("msg", "注册成功");
	    result.put("id",pk.toString() );
	    
	    //TODO  发送邮件
	    //拼写 url  和动态吗 放入  redis  等待激活
	     String randomcode = EncryptTool.md5Hex(EncryptTool.sha1HEX(DateUtils.getCurrentStringDateYYMDHMSS()) );
	     //String checkurl = "http://www.drm.com.cn/regist/checkeadd?checkemail="+randomcode+"&rdid="+user.getUserId().toString();
	     
	      //说明  激活回调
	     String domain = ConfigUtil.getString( "feedback.domain" );
	     String checkurl = domain+ "/register/activeadd?checkemail="+randomcode+"&rdid="+user.getUserId().toString();
	     Map paramMap = new HashMap();
	     paramMap.put("checkURL", checkurl);
	     paramMap.put("imgpath", imgbasePath );
	     paramMap.put("csspath", cssbasePath );
	     paramMap.put("jsbasePath", jsbasePath );
	     
	     String emailContents = FreeMarkerUtils.getTemplateContent("/ftlcontents", "email_act2", paramMap);
	     
	    boolean sendemailyn =  sendEmail("德瑞姆心理学院注册通知",emailContents,user.getEmailAddr());
	  
	    if(!sendemailyn)
	    {
	    	logger.error("发送邮件结果："+sendemailyn);
	    }

	    result.put("mail_addr", user.getEmailAddr());
	    result.put("randomcode", randomcode);
	    
	    // TODO 将验证吗放到 redis缓存保存 2小时  失效  ，，这个验证码 ，激活的时候使用， 
	    boolean redisyn = redis.putKV(randomcode, pk.toString());
	    boolean redisex = redis.setExiperse(randomcode, 60*60*2);
	    logger.error("放redis结果："+redisyn +"redisex=:"+redisex);
	    
        return JsonUtil.toJson(result);
	}

	
	/**
	 * 邮件验证  ，  repit 把原来的连接再次提交，病也加入  repit 参数=Y 表示 ，重新发送
	 * @param checkemail
	 * @param rdid
	 * @param repit  
	 * @return
	 * @throws Exception 
	 * @throws NoSuchAlgorithmException 
	 */
    @RequestMapping(value = "/activeadd")
  //  @ResponseBody  增加这个 就是 返回 json 
    public /*Map*/ModelAndView getSelectListVal( @NotNull @RequestParam(required = true)  String checkemail
    		, @NotNull @RequestParam(required = true)  String rdid 
    		, @RequestParam(required = false)  String repit
            , @RequestParam(required = false)  String newemail
     ) throws NoSuchAlgorithmException, Exception {
    	 Map result = new  HashMap();
    	 result.put("imgpath", imgbasePath );
    	 result.put("csspath", cssbasePath );
    	 
    	 
        //TODO	获取ID  如果失效  返回失败，如果成功返回注册成功， 失败  点击按钮  重新发送
        String  userid = redis.getKV(checkemail );
        ModelAndView view = null;
        //第一次进入 不是重新发送
        if(userid==null){
        	//时间到期 失效 ，重新发送
        	result.put("code", 0);
       	    result.put("msg", "激活码失效请点击按钮重新发送");
        }else  if("Y".equals(repit ) && NumberUtils.isDigits(rdid)){
        	 //重新发送邮件
        	//查询用户 重新发送邮件
        	User user = this.hibernateSupport.findUniqueBy(User.class, "userId", NumberUtils.toLong(rdid ));
        	//拼写 url  和动态吗 放入  redis  等待激活
   	     	String randomcode = EncryptTool.md5Hex(EncryptTool.sha1HEX(DateUtils.getCurrentStringDateYYMDHMSS()) );
   	     	//String checkurl = "http://www.drm.com.cn/regist/checkeadd?checkemail="+randomcode+"&rdid="+user.getUserId().toString();
   	       
	   	     String domain = ConfigUtil.getString( "feedback.domain" );
		     String checkurl = domain+ "/register/activeadd?checkemail="+randomcode+"&rdid="+user.getUserId().toString();
		     Map paramMap = new HashMap();
		     paramMap.put("checkURL", checkurl);
		    //发送email  将html 页面发送
		     String emailContents = FreeMarkerUtils.getTemplateContent("/ftlcontents", "email_act2", paramMap);
   	     	
   	     	
        	boolean sendemailyn =  sendEmail("德瑞姆心理学院注册通知",emailContents,user.getEmailAddr());
        	//再次放入缓存
        	redis.putKV(randomcode,user.getUserId().toString());
     	    redis.setExiperse(randomcode, 60*60*2);
        	
     	    if(sendemailyn)
     	    {
     	    	logger.error("发送邮件结果："+sendemailyn);
     	    	result.put("code", 1);
           	    result.put("msg", "邮件发送成功");
           	    view = new ModelAndView("email_suc",result);
     	    }else{
     	    	result.put("code", 0);
           	    result.put("msg", "发送邮件失败请在此点击");
           	    view = new ModelAndView("email_fail",result);
           	}
        	
        	
        	return  view;
        }
        
        
    	User user = this.hibernateSupport.findUniqueBy(User.class, "userId", NumberUtils.toLong(rdid ));
        
    	if(user!=null){
    		user.setUserAvtive(1);
    		this.hibernateSupport.saveOrUpdate(user );
    		result.put("code", 0);
       	    result.put("msg", "账户已经激活");
       	    view = new ModelAndView("email_suc",result);
    	}else{
    		result.put("code", 0);
       	    result.put("msg", "账户激活失败");
       	    view = new ModelAndView("email_fail",result);
    	}
  	  
    	//资源 图片js css
		putResourceSrc(view);	
        return view;
    }
    
    /**
     * 得到页面上省和城市的列表
     * 
     * @return map
     */
    @RequestMapping(value = "/chinacity")
    @ResponseBody
    public Map getSelectListVal() {
        Map<String, ArrayList> maps = Maps.newHashMap();

        // the province code and name
        ArrayList<CodeName> codeNameList = new ArrayList<CodeName>();
        // the province code and name
        ArrayList<CityCodeName> cityCodeNameList = new ArrayList<CityCodeName>();
        ArrayList<ProvinceCity> provinceList  = this.areaService.getProvinceCityList();
        for (ProvinceCity pCity : provinceList) {
            if (pCity.getLevel() == 1) {
                CodeName codeName = new CodeName(pCity.getCode(), pCity.getName());
                codeNameList.add(codeName);
            } else if (pCity.getLevel() == 2) {
                CityCodeName cityCodeName = new CityCodeName();
                cityCodeName.setCode(pCity.getCode());
                cityCodeName.setName(pCity.getName());
                cityCodeName.setParent_code(pCity.getParent_code());
                cityCodeNameList.add(cityCodeName);
            } else {
                // do nothing
            }
        }
        maps.put("province", codeNameList);
        maps.put("city", cityCodeNameList);
        
        return maps;
    }


    
    
    private boolean  sendEmail(String subject,String content,String sendaddress){
    	 MailSenderInfo mailInfo = new MailSenderInfo();   
	     mailInfo.setMailServerHost(  ConfigUtil.getString("sendmail.host")/*"smtp.126.com"*/);   
	     mailInfo.setMailServerPort(ConfigUtil.getString("sendmail.port") /*"25"*/);   
	     mailInfo.setValidate(true);  
	     mailInfo.setUserName(ConfigUtil.getString("sendmail.username") /*"tianshuxiaoleitest@126.com"*/);
	     mailInfo.setPassword(ConfigUtil.getString("sendmail.password") /*"12qwaszx"*/);
	     mailInfo.setFromAddress(ConfigUtil.getString("sendmail.fromaddress") /*"tianshuxiaoleitest@126.com"*/);   
	     mailInfo.setToAddress(sendaddress/*"tianshuxiaolei@163.com"*/);   
	     mailInfo.setSubject(subject);   
	     mailInfo.setContent(content);   
	     SimpleMailSender.getInstance().sendHtmlMail(mailInfo);
	     if(mailInfo.getState() == 200 ){
		    	//邮件发送成功
		    return true;
	     }else{
	         return false;
	    	//邮件发送失败  重新发送
	     }
    }
}
